package wei.xinya.core.write;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Date;

public class WriteFile {
    public static void main(String[] args) {
        String test = "http://192.168.7.250:9999/test/Bing壁纸/FrostLeaves_ZH-CN6851974281_UHD.jpg";

        String encodeUrl = encodeUrl(test);

        writeFile(encodeUrl);
    }

    /**
     * URL特殊符号转义
     *
     * @param url URL字符串
     * @return 转义后URL
     */
    private static String encodeUrl(String url) {
        String encodeUrl = "";

        if (StringUtils.isBlank(url)) {
            return encodeUrl;
        }

        try {
            encodeUrl = URLEncoder.encode(url, StandardCharsets.UTF_8.toString());
            System.out.println("转义后Url：" + encodeUrl);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return encodeUrl;
    }

    /**
     * 根据url获取文件流
     *
     * @param url 图片url
     */
    public static void writeFile(String url) {
        URL u = null;

        try {
            u = new URL(URLDecoder.decode(url, StandardCharsets.UTF_8.toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (u == null) {
            System.out.println("url无效");
            return;
        }

        try (InputStream inputStream = u.openStream()) {
            String fileName = getFileName(".jpg");
            Path path = Paths.get("C:\\Users\\wxy\\Desktop\\" + fileName);
            Files.write(path, toByteArray(inputStream), StandardOpenOption.CREATE);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件流转为byte数据
     *
     * @param input 文件流
     * @return byte数据
     */
    private static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 10];
        int num;
        while ((num = input.read(buffer)) != -1) {
            output.write(buffer, 0, num);
        }
        return output.toByteArray();
    }

    /**
     * 统一生成文件名
     *
     * @param suffix 后缀
     * @return 文件名
     */
    public static String getFileName(String suffix) {
        Date date = new Date();
        return RandomStringUtils.randomAlphanumeric(10) + date.getTime() + suffix;
    }
}
